import axios, {AxiosInstance, AxiosResponse, InternalAxiosRequestConfig} from 'axios';
import { Session } from '/@/utils/storage';
import { useMessage, useMessageBox } from '/@/hooks/message';
import qs from 'qs';
import other from './other';
import { useUserInfo } from '/@/stores/userInfo';
import errorCode from './errorCode';
import { logout } from '../api/login';
import { validateNull } from './validate';

let isRefreshing = false; // 当前是否在刷新token
let retryRequests: any[] = []; // 记录在刷新token过程中，调用的接口，等待token刷新完成后，再重新调用

/**
 * 创建并配置一个 Axios 实例对象
 */
const service: AxiosInstance = axios.create({
	baseURL: '',
	timeout: 50000, // 全局超时时间
    paramsSerializer: {
        serialize: (params: any) => {
            return qs.stringify(params, {arrayFormat: 'repeat'});
        }
    }
});

/**
 * Axios请求拦截器，对请求进行处理
 * 1. 序列化get请求参数
 * 2. 统一增加Authorization和TENANT-ID请求头
 * 3. 自动适配单体、微服务架构不同的URL
 * @param config AxiosRequestConfig对象，包含请求配置信息
 */
service.interceptors.request.use(

	(config: InternalAxiosRequestConfig) => {
		if (config.url.indexOf('geoserver') == -1 && !config.url.startsWith('http')) {
			if (config.url.substring(0, 1) == '/') {
				config.url = `app${config.url}`;
			} else {
				config.url = `app/${config.url}`;
			}
		}

		// 统一增加Authorization请求头, skipToken 跳过增加token
		const token = Session.getToken();
		if (token && !config.headers?.skipToken) {
			config.headers![CommonHeaderEnum.AUTHORIZATION] = `Bearer ${token}`;
		}

		// 统一增加TENANT-ID请求头
		const tenantId = Session.getTenant();
		if (tenantId && !config.headers["TENANT-ID"]) {
			config.headers![CommonHeaderEnum.TENANT_ID] = tenantId;
		}

		// 请求报文加密
		if (config.headers![CommonHeaderEnum.ENC_FLAG]) {
			const enc = other.encryption(JSON.stringify(config.data), import.meta.env.VITE_PWD_ENC_KEY);
			config.data = {
				encryption: enc,
			};
		}

		// 自动适配单体和微服务架构不同的URL
		config.url = other.adaptationUrl(config.url);

		// 处理完毕，返回config对象
		return config;
	},
	(error) => {
		// 对请求错误进行处理
		return Promise.reject(error);
	}
);

/**
 * 响应拦截器处理函数
 * @param response 响应结果
 * @returns 如果响应成功，则返回响应的data属性；否则，抛出错误或者执行其他操作
 */
const handleResponse = (response: AxiosResponse<any>) => {
	if (response.data.code === 1) {
		useMessage().error(response.data.msg);
		throw response.data;
	}

	// 针对密文返回解密
	if (response.data.encryption) {
		const originData = JSON.parse(other.decryption(response.data.encryption, import.meta.env.VITE_PWD_ENC_KEY));
		response.data = originData;
		return response.data;
	}

	return response.data;
};

/**
 * 添加 Axios 的响应拦截器，用于全局响应结果处理
 */
service.interceptors.response.use(handleResponse, async (error) => {
	const status = Number(error.response.status) || 200;
	const message = error.response.data.msg || errorCode[status] || errorCode['default'];
	if(status === 503){
		useMessage().error(error.response.data.msg);
	}else if (status === 424) {
		//刷新token，刷新失败再跳转登录页
		if (!isRefreshing) {
			isRefreshing = true;
			//是否微信
			const isWx = Session.get('isWxLogin') || false;
			if (isWx) {
				await useUserInfo()
					.refreshTokenForWx()
					.then(() => {
						isRefreshing = false;
					})
					.catch(() => {
						wx.miniProgram.postMessage({
							data: {
								loginOut: true,
							},
						});
						wx.miniProgram.navigateBack({
							delta: 10,
						});
					});
			} else {
				await useUserInfo()
					.refreshToken()
					.then(() => {
						console.log(111)
						isRefreshing = false;
					})
					.catch(async () => {
						await logout()
						useMessage().error('令牌状态已过期，请重新登录')
						Session.clear(); // 清除浏览器全部临时缓存
						useUserInfo().clearUserInfos()
						const isPcLogin = Session.get('isPcLogin')
						if (isPcLogin) {
							window.location.href = '/#/login'; // 去登录页
						} else {
							window.location.href = '/'; // 去登录页
						}
						return
					});
			}
			if (retryRequests.length > 0) {
				retryRequests.forEach((fun) => fun());
				retryRequests = []
			}
			let token = Session.getToken();
			if (validateNull(token)) return Promise.reject(error.response.data);
			error.config.headers.Authorization = `Bearer ${token}`;
			return service(error.config);
		} else {
			return new Promise((resolve) => {
				retryRequests.push(() => {
					let token = Session.getToken();
					if (validateNull(token)) return
					error.config.headers.Authorization = `Bearer ${token}`;
					resolve(service(error.config));
				});
			});
		}
	}else if (status !== 200) {
		useMessage().error(message);
	}
	return Promise.reject(error.response.data);
});

// 常用header
export enum CommonHeaderEnum {
	'TENANT_ID' = 'TENANT-ID',
	'ENC_FLAG' = 'Enc-Flag',
	'AUTHORIZATION' = 'Authorization',
}

// 导出 axios 实例
export default service;
